package com.thread.learn.thread4;

public class Sequence {

	private int value;

	/**
	 * synchronized 放在不同方法上，内置锁就是当前类的实例
	 * @return
	 */
	public synchronized int getNext() {
		return value++;
	}
	
	/**
	 * synchronized 放在静态方法，内置锁是单前的class字节码对象
	 * @return
	 */
	public static synchronized int getPrevious() {
//		return value --;
		return 0;
	}

	public int number() {
		
		synchronized (Sequence.class) {
			if(value >0) {
				return value;
			}else {
				return -1;
			}
		}
	}
	
	public static void main(String[] args) {
		Sequence s = new Sequence();
		/*
		 * while (true) { System.out.println(s.getNext()); }
		 */

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();

	}

}
